<!-- 业务服务资源管理 -->
<template>
	<div>
		<!-- 搜索表单 -->
		<el-form :model="searchFormData" :inline="true" :label-width="120" style="width: 100%">
			<el-row :gutter="20">
				<el-col :span="5">
					<el-form-item label="服务资源类型" prop="identifyType">
						<el-select v-model="searchFormData.identifyType" placeholder="请选择服务资源类型" clearable>
							<el-option v-for="item in options.typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="确认状态" prop="isConfirm">
						<el-select v-model="searchFormData.isConfirm" placeholder="请选择确认状态" clearable>
							<el-option v-for="item in options.statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="资源类别" prop="type">
						<el-select v-model="searchFormData.type" placeholder="请选择资源类别" clearable>
							<el-option v-for="item in options.categoryOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="服务资源编码" prop="resourceCode">
						<el-input v-model="searchFormData.resourceCode" placeholder="请输入服务资源编码" clearable class="yd-input" />
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="识别匹配串" prop="identifyStr">
						<el-input v-model="searchFormData.identifyStr" placeholder="请输入识别匹配串" clearable class="yd-input" />
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="父服务资源编码" prop="parentResourceCode">
						<el-input v-model="searchFormData.parentResourceCode" placeholder="请输入父服务资源编码" clearable class="yd-input" />
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="协议资源编码" prop="protocolCode">
						<el-select v-model="searchFormData.protocolCode" placeholder="请选择协议资源编码" clearable>
							<el-option v-for="item in agreementResourceList" :key="item.value" :label="item.value" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item>
						<el-button type="primary" icon="Search" @click="handlerQuery">查 询</el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>

		<!-- 数据列表 -->
		<YdTable
			:formData="searchFormData"
			:tableConfig="tableConfig"
			:tableData="tableData.data"
			@sizeChangeHandler="handlerQuery"
			@currentChangeHandler="handlerQuery"
			@sortChangeHandler="handlerQuery"
			@selectionChangeHandler="handlerSelectionChange"
		>
		</YdTable>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog :title="dialog.addOrUpdate.title" v-model="dialog.addOrUpdate.open" width="600px" append-to-body center>
			<el-form ref="addOrUpdateForm" :model="dialog.addOrUpdate.form" :rules="dialog.addOrUpdate.rule" label-width="120px">
				<el-form-item label="识别匹配串" prop="identifyStr">
					<el-input v-model="dialog.addOrUpdate.form.identifyStr" placeholder="请输入识别匹配串"></el-input>
				</el-form-item>
				<el-form-item label="匹配串类型" prop="identifyType">
					<el-select v-model="dialog.addOrUpdate.form.identifyType" placeholder="请选择匹配串类型" style="width: 100%">
						<el-option v-for="(option, index) in typeOptions" :key="index" :label="option.label" :value="option.value"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="协议资源编码" prop="protocolCode">
					<el-select v-model="dialog.addOrUpdate.form.protocolCode" placeholder="请选择协议资源编码" style="width: 100%">
						<el-option label="请选择" :value="undefined"></el-option>
						<el-option v-for="(option, index) in agreementResourceList" :key="index" :label="option.value" :value="option.value"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="资源类别" prop="type">
					<el-select v-model="dialog.addOrUpdate.form.type" placeholder="请选择资源类别" style="width: 100%">
						<el-option v-for="(option, index) in categoryOptions" :key="index" :label="option.label" :value="option.value"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="父服务资源编码" prop="">
					<el-input v-model="dialog.addOrUpdate.form.parentResourceCode" placeholder="请输入父服务资源编码"></el-input>
				</el-form-item>
			</el-form>
			<!-- class="dialog-footer" -->
			<template #footer>
				<el-button type="primary" @click="handlerSubmit" :loading="dialog.addOrUpdate.btnLoading">确 定</el-button>
				<el-button @click="closeAddOrUpdateDialog">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="BusinessSourceManage" lang="tsx">
import { businessServerResourceOptions } from '@/utils/admin/options';
import { reactive, ref, getCurrentInstance, onMounted } from 'vue';
import {
	queryAgreementResourceList,
	list,
	add,
	edit,
	remove,
	confirmResource,
	cancelResource,
} from '@/api/admin/businessSourceManage/businessSourceManage';
import { getToken } from '@/utils/auth';
import { useRouter } from 'vue-router';

const { proxy }: any = getCurrentInstance();
const router = useRouter();

// 宏协议列表
const agreementResourceList = ref([] as any[]);
// 选项
let options: any = reactive(businessServerResourceOptions());

// 搜索表单数据
let searchFormData = reactive<anyObj>({
	// 默认按启动时间降序
	orderByColumn: 'updateTime',
	isAsc: 'desc',
	// 4.1
	resourceCode: '',
	identifyStr: '',
	identifyType: '',
	ids: '',
	isConfirm: '',
	parentResourceCode: '',
	protocolType: '',
	protocolCode: '',
	type: '',
	pageSize: 10,
	pageNum: 1,
});
// 列表配置
console.log(proxy, 'proxy');

let tableConfig = reactive<anyObj>({
	url: list,
	columns: [
		{
			label: '服务资源编码',
			prop: 'resourceCode',
			width: 180,
			render: (row: any, val: any) => {
				if (proxy.checkPermi(['indicator:management:detail'])) {
					return (
						<div onClick={resourceCodeClick.bind(this, row, false)} class="color-primary" style="cursor: pointer">
							<span>{val}</span>
						</div>
					);
				}
			},
		},
		{
			label: '父服务资源编码',
			prop: 'parentResourceCode',
			width: 180,
			render: (row: any, val: any) => {
				if (proxy.checkPermi(['indicator:management:detail'])) {
					return (
						<div onClick={resourceCodeClick.bind(this, row, true)} class="color-primary" style="cursor: pointer">
							<span>{val}</span>
						</div>
					);
				}
			},
		},
		{
			label: '匹配串',
			prop: 'identifyStr',
			showOverFlowToolTip: true,
		},
		{
			label: '匹配串类型',
			prop: 'identifyType',
			width: 100,
			formatter: (row: any, val: any) => {
				return typeOptionsFormatter(row.identifyType);
			},
		},
		{
			label: '协议资源编码',
			prop: 'protocolCode',
			width: 200,
		},
		{
			label: '确认状态',
			prop: 'isConfirm',
			width: 80,
			formatter: (row: any, val: any) => {
				return options.statusOptionsMap[val];
			},
		},
		{
			label: '确认类型',
			prop: 'type',
			width: 80,
			formatter: (row: any, val: any) => {
				return options.confirmOptionsMap[val];
			},
		},
		{
			label: '启用时间',
			prop: 'updateTime',
			width: 160,
			sortable: true,
		},
		{
			label: '资源类别',
			prop: 'type',
			width: 160,
			formatter: (row: any, val: any) => {
				return options.categoryOptionsMap[val];
			},
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['business:resource:add'], handler: () => handlerAdd() },
		{ name: '修改', icon: 'yd-icon-edit', disable: 'single', permi: ['business:resource:edit'], handler: () => handlerEdit() },
		{ name: '删除', icon: 'yd-icon-delete', disable: 'multiple', permi: ['business:resource:delete'], handler: () => handlerDelete() },
		{ name: '确认', icon: 'yd-icon-confirm', disable: 'multiple', permi: ['business:resource:confirm'], handler: () => handlerConfirmResource() },
		{ name: '取消', icon: 'yd-icon-cancel', disable: 'multiple', permi: ['business:resource:cancel'], handler: () => handlerCancelResource() },
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	// pagination: true,
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
	pageSizes: [10, 20, 30, 50, 100, 200, 500],
});
// 列表数据
let tableData = reactive({
	data: [],
	total: 0,
});
//dialog下拉框赋值
const typeOptions = ref([
	{ label: '请选择', value: undefined },
	{ label: 'URL', value: 1 },
	{ label: 'API', value: 2 },
	{ label: 'SQL', value: 3 },
]);
function typeOptionsFormatter(val: number): string {
	switch (val) {
		case 1:
			return typeOptions.value[val].label;
		case 2:
			return typeOptions.value[val].label;
		case 3:
			return typeOptions.value[val].label;
		default:
			return '';
	}
}
function resourceCodeClick(row: any, isParentCode = false) {
	router.push({
		path: '/management/indicatorManage/proprietaryIndicatorManage/detail',
		query: {
			resourceCode: isParentCode ? row.parentResourceCode : row.resourceCode,
			identifyStr: row.identifyStr,
			isPackage: 1,
		},
	});
}
const categoryOptions = ref([
	{ label: '请选择', value: undefined },
	{ label: '非首端服务资源', value: 0 },
	{ label: '关键加载项服务资源', value: 1 },
	{ label: '步骤服务资源', value: 2 },
]);
function categoryOptionsFormatter(val: number): string {
	switch (val) {
		case 0:
			return categoryOptions.value[val].label;
		case 1:
			return categoryOptions.value[val].label;
		case 2:
			return categoryOptions.value[val].label;
		default:
			return '';
	}
}
// 选择的行数据ids
const selectedIds: any = ref(null);
// 选择的行数据
const selected: any = ref(null);
let dialog = reactive<any>({
	addOrUpdate: {
		// 打开状态
		open: false,
		// 标题
		title: '',
		// 表单数据
		form: {},
		// 按钮加载中状态
		btnLoading: false,
		// 表单校验规则
		rule: {
			identifyStr: [{ required: true, message: '识别匹配串不能为空', trigger: 'blur' }],
			identifyType: [{ required: true, message: '匹配串类型必选', trigger: 'change' }],
			protocolCode: [{ required: true, message: '协议资源编码必选', trigger: 'change' }],
			type: [{ required: true, message: '资源类别必选', trigger: 'change' }],
			parentResourceCode: [{ pattern: /^[a-z0-9]{16}$/, message: '请输入16位小写字母或数字', trigger: 'blur' }],
		},
	},
	imp: {
		// ref
		ref: 'uploadRef',
		// 打开状态
		open: false,
		// 标题
		title: '导入',
		// 上传请求头
		headers: {
			Authorization: 'Bearer ' + getToken(),
		},
		// 最多导入数
		limit: 1,
	},
});

onMounted(() => {
	dialog.addOrUpdate.form.identifyType = undefined;
	dialog.addOrUpdate.form.protocolType = undefined;
	dialog.addOrUpdate.form.type = undefined;

	// 查询宏协议资源列表
	queryAgreementResourceList().then((res: ApiResponse | any) => {
		agreementResourceList.value = [];
		agreementResourceList.value = res.data;
		// proxy.$refs.resourceCodingSel.setOptions(agreementResourceList.value);
	});
	handlerQuery();
});

/**
 * 关闭新增或修改弹出层
 */
function closeAddOrUpdateDialog() {
	dialog.addOrUpdate.open = false;
}
/**
 * 选择行数据
 */
function handlerSelectionChange(selects: any) {
	selectedIds.value = selects.map((item: any) => item.id);
	selected.value = selects;
}
/**
 * 搜索
 */
function handlerQuery() {
	tableConfig.loading = true;
	Object.keys(searchFormData).forEach((key: string) => {
		if (searchFormData[key] === '') {
			delete searchFormData[key];
		}
	});
	list(searchFormData)
		.then((res: ApiResponse | any) => {
			tableConfig.loading = false;
			if (res.code !== 0) {
				return;
			}
			if (res.data !== null) {
				tableData.data = res.data.records;
				tableData.total = res.data.total;
				tableConfig.pagination.total = res.data.total;
			}
		})
		.catch((e: any) => {
			tableConfig.loading = false;
		});
}
/**
 * 表单提交
 */
function handlerSubmit() {
	let res = agreementResourceList.value.find((item: any) => item.value === dialog.addOrUpdate.form.protocolCode);
	dialog.addOrUpdate.form.protocolType = res && res.label;

	if (dialog.addOrUpdate.title === '新增') {
		handlerAdd();
	} else {
		handlerEdit();
	}
}
/**
 * 新增
 */
function handlerAdd() {
	let sign;
	// 判断窗口是否打开
	if (!dialog.addOrUpdate.open) {
		// 表单重置
		if (sign !== 'SET_FORM') {
			dialog.addOrUpdate.form = {};
			// proxy.resetForm('addOrUpdateForm');
		}
		// 标题
		dialog.addOrUpdate.title = '新增';
		// 打开窗口
		dialog.addOrUpdate.open = true;
		return;
	}
	// 校验参数
	proxy.$refs['addOrUpdateForm'].validate((valid: boolean | any) => {
		if (!valid) {
			return;
		}
		// 调用接口
		dialog.addOrUpdate.btnLoading = true;
		dialog.addOrUpdate.form.isConfirm = '0';
		add(dialog.addOrUpdate.form).then((res: ApiResponse | any) => {
			dialog.addOrUpdate.btnLoading = false;
			if (res.code !== 0) {
				proxy.$modal.msgError(res.msg);
				return;
			}
			// 关闭弹出层
			closeAddOrUpdateDialog();
			// 刷新列表
			// searchFormData.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('新增成功！');
		});
	});
}
/**
 * 修改
 */
function handlerEdit() {
	// 判断窗口是否打开
	if (!dialog.addOrUpdate.open) {
		// 数据回显，数据需要拷贝一下
		const d = JSON.parse(JSON.stringify(selected.value[0]));

		dialog.addOrUpdate.form = d;
		console.log(dialog.addOrUpdate.form, 'dd');
		// 标题
		dialog.addOrUpdate.title = '修改';
		// 打开窗口
		dialog.addOrUpdate.open = true;
		return;
	}
	// 校验参数
	proxy.$refs['addOrUpdateForm'].validate((valid: boolean) => {
		if (!valid) {
			return;
		}
		// 调用接口
		dialog.addOrUpdate.btnDisabled = true;
		edit(dialog.addOrUpdate.form).then((res: ApiResponse | any) => {
			dialog.addOrUpdate.btnDisabled = false;
			if (res.code !== 0) {
				proxy.$modal.msgError(res.msg);
				return;
			}
			// 关闭弹出层
			closeAddOrUpdateDialog();
			// 刷新列表
			// searchFormData.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('修改成功！');
		});
	});
}
/**
 * 删除
 */
function handlerDelete() {
	proxy.$modal
		.confirm('是否确认删除所选项?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
		.then(() => {
			// 调用接口
			return remove(selectedIds.value);
		})
		.then(() => {
			// 刷新列表 计算是否要查询上一页的数据
			if (tableData.total && searchFormData.pageSize) {
				// 删除后的总条数
				let totalCount = tableData.total - selectedIds.length;
				// 计算删除后的总页数
				let totalPage = Math.ceil(totalCount / searchFormData.pageSize);
				// 如果删除后的总页数小于1, 置为1
				totalPage = totalPage < 1 ? 1 : totalPage;
				// 判断删除前的页数是否大于删除后的总页数, 计算当前页应该是多少赋值给查询表单
				searchFormData.pageNum = searchFormData.pageNum > totalPage ? totalPage : searchFormData.pageNum;
			} else {
				searchFormData.pageNum = 1;
			}
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('删除成功！');
		});
}

// 确认服务资源
function handlerConfirmResource() {
	proxy.$modal
		.confirm('是否确认所选资源?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'info',
		})
		.then(() => {
			// 调用接口
			return confirmResource(selected.value.map((item: any) => item.resourceCode).join(','));
		})
		.then(() => {
			// 刷新列表
			// searchFormData.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('确认成功！');
		})
		.catch(function () {});
}
// 取消服务资源
function handlerCancelResource() {
	proxy.$modal
		.confirm('是否取消所选资源?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'info',
		})
		.then(() => {
			// 调用接口
			return cancelResource(selected.value.map((item: any) => item.resourceCode));
		})
		.then(() => {
			// 刷新列表
			// searchFormData.pageNum = 1;
			handlerQuery();
			// 提示
			proxy.$modal.msgSuccess('取消成功！');
		})
		.catch(function () {});
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped></style>
